//****************************************************************
//* Copyright (c) 2008 Ford Motor Company. All Rights Reserved.
//*
//* $$Workfile:   EconomicSourceAction.java  $$
//* $$Revision:   1.1  $$
//* $$Author:   JLOPE262  $$
//* $$Date:   Nov 21 2008 14:26:40  $$
//*
//*****************************************************************
package ar.com.ford.it.fullEconomics.view.action;

import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.facade.EconomicSourceFacade;
import ar.com.ford.it.fullEconomics.persistence.dto.Teese02Econsource;
import ar.com.ford.it.fullEconomics.view.form.EconomicSourceForm;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.facade.FacadeProvider;
import ar.com.ford.it.webengine.struts.AbstractBaseAction;
import ar.com.ford.it.webengine.struts.FordActionMapping;
import ar.com.ford.it.webengine.websession.WebSession;

public class EconomicSourceAction extends AbstractBaseAction {

    /**
     * Setea el mensaje de "busqueda sin resultados" cuando la busqueda no trae
     * resultados
     * 
     * @param request
     * Request donde se guarda el mensaje
     */
    private void searchWithNoResults(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("message.noResults")));
        saveMessages(request, am);
    }

    /**
     * Setea el mensaje que se refiere a que el Economic Source no puede ser borrado dado
     * que hay economics que hacen referencia a el
     * 
     * @param request
     */
    private void setErrorEconomicSourceHasReferences(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "customMessage", messageResources
                        .getMessage("economicSource.error.hasReferences")));
        saveErrors(request, am);                
    }
    
    /**
     * Setea el mensaje de Economic Source repetido
     * 
     * @param request
     */
    private void setErrorEconomicSourceAlreadyExists(HttpServletRequest request) {
        ActionMessages am = new ActionMessages();
        MessageResources messageResources = (MessageResources) getResources(request);

        am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                "error.duplicateItem.f", messageResources
                        .getMessage("economicSource")));
        this.saveErrors(request, am);
    }    
    
    /**
     * Resetea el formulario y envia a la pagina inicial de Economic Sources
     * 
     */
    public ActionForward initPage(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicSourceForm form = (EconomicSourceForm) actionForm;

        form.resetForm();
        return mapping.findForward("success");
    }

    /**
     * Se encarga del manejo de la busqueda de Economic Sources
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward findEconomicSources(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {                
        
        ActionMessages am = new ActionMessages();
        EconomicSourceForm form = (EconomicSourceForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession.getUser();
        EconomicSourceFacade facade = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);
        
        try {
            Collection<Teese02Econsource> res;
            res = facade.findEconomicSources(form.getCodeFind(), form
                    .getNameFind(), user.getTeesg01Plant());

            if (res.isEmpty()) {
                searchWithNoResults(request);
            }

            form.setEconomicSources(res);
            form.clearCreateUpdateFields();
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }        
        return mapping.findForward("success");
    }

    /**
     * Setea los campos de edicion de Economic Sources con los valores del
     * Economic Source seleccionado mediante el listado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward editEconomicSource(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicSourceForm form = (EconomicSourceForm) actionForm;

        form.setEconomicSourceForEdit(form.getEconomicSourceSelected());
        return mapping.findForward("success");
    }

    /**
     * En caso de que se haya seleccionado algun Economic Source del listado,
     * entonces lo actualiza, sino llama al metodo encargado de crear el
     * Economic Source
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward createUpdateEconomicSource(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        
        ActionMessages am = new ActionMessages();
        EconomicSourceForm form = (EconomicSourceForm) actionForm;
        FullEconomicsWslxUser user = (FullEconomicsWslxUser) webSession
                .getUser();
        EconomicSourceFacade facade = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);

        try {
            if (form.getCode() == null) {
                if (!facade.economicSourceNameAlreadyExists(form.getName(), user.getTeesg01Plant())) {
                    facade.createEconomicSource(form.getEconomicSourceForCreate(),
                            user);
                } else {
                    this.setErrorEconomicSourceAlreadyExists(request);
                }
            } else {
                if (!facade.economicSourceNameAlreadyExists(form.getName(), user.getTeesg01Plant())) {
                    facade.updateEconomicSource(form
                            .getEconomicSourceForUpdate(form
                                    .getEconomicSourceSelected()), user);
                } else {
                    this.setErrorEconomicSourceAlreadyExists(request);
                }
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }
        
        return mapping.findForward("success");
    }

    /**
     * Elimina el Economic Source seleccionado
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward deleteEconomicSource(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        
        ActionMessages am = new ActionMessages();
        EconomicSourceForm form = (EconomicSourceForm) actionForm;
        EconomicSourceFacade facade = (EconomicSourceFacade) FacadeProvider
                .getFacade(request, EconomicSourceFacade.class);
        
        try {
            if (facade.economicSourceCanBeDeleted(form.getEconomicSourceSelected())) {
                facade.deleteEconomicSource(form.getEconomicSourceSelected());
            } else {
                setErrorEconomicSourceHasReferences(request);
            }
        } catch (FullEconomicsException e) {
            am.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getMessageResource()));
            saveErrors(request, am);
        }
        return mapping.findForward("success");
    }
    
    /**
     * Limpia los campos de creacion de Economic Sources
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward cleanEconomicSource(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicSourceForm form = (EconomicSourceForm) actionForm;
        
        form.clearCreateUpdateFields();
        return mapping.findForward("success");
    }

    /**
     * Limpia los campos de busqueda de Economic Source
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @param webSession
     * @param msgs
     * @param warns
     * @param errorMsgs
     * @return
     */
    public ActionForward cleanFindEconomicSource(FordActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response, WebSession webSession,
            ActionMessages msgs, ActionMessages warns, ActionMessages errorMsgs) {
        EconomicSourceForm form = (EconomicSourceForm) actionForm;
        
        form.cleanFindFields();
        return mapping.findForward("success");
    }
        
}
